//
//  PEChioceCountyViewController.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2023/7/14.
//

#import "RHCountryCodeVC.h"
#import "RHWindowTipManage.h"
#import "RHCountryRegionCodeModel.h"

@interface RHCountryCodeVC ()<UIPickerViewDataSource,UIPickerViewDelegate>

@property (nonatomic ,strong) UIPickerView *pickerView;

@property (nonatomic ,copy) NSArray *provinceArr;//省,州
@property (nonatomic ,copy) NSArray *cityArr;//市
@property (nonatomic ,copy) NSArray *ereaArr;//区

@property(nonatomic,copy)NSString *regionCode;//区域编码
@property(nonatomic,copy)NSString *partnerId;//合作id

@property(nonatomic,copy)NSString *selected_regionCode;//选择的区域编码
@property(nonatomic,copy)NSString *selected_regionName;//选择的区域编码
@end

@implementation RHCountryCodeVC

- (instancetype)initWithRegionCode:(NSString*)regionCode partnerID:(NSString*)partnerId{
    
    self = [super init];
    if (self) {
        _regionCode = regionCode;
        _partnerId = partnerId;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self getCountryCodeWithRegionCode:self.regionCode level:self.partnerId];
}
//获取国家 省 市 区 代码
-(void)getCountryCodeWithRegionCode:(NSString*)regionCode level:(NSString*)level
{
    NSDictionary *para = @{@"regionCode":regionCode,@"level":level};
    [QMUITips showLoadingInView:self.view];
    [RHCountryRegionCodeModel startGetWithCompletionAPIKey:H_regionCode argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
     
        //区
        self.provinceArr = resultModel.data;
        self.cityArr = nil;
        self.ereaArr = nil;
        
        
        
        if(self.provinceArr.count>0){
            //可以申请的还往下展开
            RHCountryRegionCodeModel *province = self.provinceArr[0];
            if(province.apply){
                self.cityArr = ((RHCountryRegionCodeModel*)self.provinceArr[0]).regionVoList;
            }
            if(self.cityArr.count>0){
                RHCountryRegionCodeModel *city = self.cityArr[0];
                if(city.apply){
                    self.ereaArr = ((RHCountryRegionCodeModel*)self.cityArr[0]).regionVoList;
                }
                
            }
        }
        [self.pickerView reloadAllComponents];
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        
    }];
}

- (void)setupUI{
    
    [self.view setBackgroundColor:[UIColor.blackColor colorWithAlphaComponent:0.3]];
    
    UIView *touchView = [[UIView alloc] init];
    [touchView setBackgroundColor:UIColor.clearColor];
    [self.view addSubview:touchView];

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
    touchView.userInteractionEnabled = YES;
    [touchView addGestureRecognizer:tap];
    
    UIView *bgView = [[UIView alloc] init];
    [bgView setBackgroundColor:kCOLOR_HEX(@"#f5f5f5")];
    [self.view addSubview:bgView];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitleColor:kCOLOR_HEX(@"#000000") forState:UIControlStateNormal];
    [btn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont boldSystemFontOfSize:16]];
    [bgView addSubview:btn];

    
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(35);
        make.right.mas_offset(-15);
        make.width.mas_equalTo(65);
        make.centerY.mas_offset(0);
    }];
    
    
    _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, kUI_WINDOW_H-(216+kTabbarSafeBottomMargin), kUI_WINDOW_W, 216+kTabbarSafeBottomMargin)];
    [_pickerView setDataSource:self];
    [_pickerView setDelegate:self];
    [_pickerView setBackgroundColor:UIColor.whiteColor];
    [self.view addSubview:_pickerView];
    
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(45);
        make.left.right.mas_offset(0);
        make.bottom.equalTo(_pickerView.mas_top);
    }];
    
    [touchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsZero);
    }];

    
    kWeakSelf;
    [tap.rac_gestureSignal subscribeNext:^(__kindof UIGestureRecognizer * _Nullable x) {
        [weakSelf hidden];
    }];
#pragma mark ---- 确定 -----
    [[btn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        if (weakSelf.selectBlock) {
        
            if(weakSelf.ereaArr.count>0){
                NSInteger idx = [weakSelf.pickerView selectedRowInComponent:2];
                RHCountryRegionCodeModel *regionModel = weakSelf.ereaArr[idx];
                if(regionModel.apply == NO){
                    [QMUITips showError:@"This area is not eligible for application"];
                    return;
                }
                weakSelf.selectBlock(idx,regionModel.regionCode,regionModel.regionName);
            }else if (weakSelf.cityArr.count>0){
                NSInteger idx = [weakSelf.pickerView selectedRowInComponent:1];
                RHCountryRegionCodeModel *regionModel = weakSelf.cityArr[idx];
                if(regionModel.apply == NO){
                    [QMUITips showError:@"This area is not eligible for application"];
                    return;
                }
                weakSelf.selectBlock(idx,regionModel.regionCode,regionModel.regionName);
            }else if (weakSelf.provinceArr.count>0){
                NSInteger idx = [weakSelf.pickerView selectedRowInComponent:0];
                RHCountryRegionCodeModel *regionModel = weakSelf.provinceArr[idx];
                if(regionModel.apply == NO){
                    [QMUITips showError:@"This area is not eligible for application"];
                    return;
                }
                weakSelf.selectBlock(idx,regionModel.regionCode,regionModel.regionName);
            }
           
        }
        [weakSelf hidden];
    }];
}

- (void)hidden{
   
    [[RHWindowTipManage shareWindowTipManage] hidden];
}


#pragma mark - UIPickerViewDataSource,UIPickerViewDelegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if(component==0){
        return self.provinceArr.count;
    }else if (component == 1){
        return self.cityArr.count;
    }else{
        return self.ereaArr.count;
    }
    
}
- (nullable NSAttributedString *)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    RHCountryRegionCodeModel *regionModel;
    if(component==0){
        regionModel = self.provinceArr[row];
    }else if (component == 1){
        regionModel = self.cityArr[row];
    }else{
        regionModel = self.ereaArr[row];
    }

    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:regionModel.regionName];
    [str addAttributes:@{NSForegroundColorAttributeName:regionModel.apply?CMainColorGreen:kRGB(140, 140, 140)} range:NSMakeRange(0, str.length)];
   
    return str;
}



- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if(component==2)return;//最后一级
    RHCountryRegionCodeModel *model;
    
    if(component == 0){
        model = self.provinceArr[row];
        //市级展开,展开显示的是第一行,再判断地区可不可以展开
        self.cityArr = model.apply? model.regionVoList : nil;
        if(self.cityArr.count > 0){
            model = self.cityArr[0];
            self.ereaArr = model.apply? model.regionVoList : nil;
        }else{
            self.ereaArr = nil;
        }
        
    }else if(component == 1){
        if(self.cityArr.count>0){
            model = self.cityArr[row];
            self.ereaArr = model.apply? model.regionVoList : nil;
        }
    }else{
        model = self.ereaArr[row];
    }
    [pickerView reloadAllComponents];
}


- (NSArray *)provinceArr{
    if (!_provinceArr) {
        _provinceArr = [NSArray array];
    }
    return _provinceArr;
}
-(NSArray *)cityArr
{
    if (!_cityArr) {
        _cityArr = [NSArray array];
    }
    return _cityArr;
}
-(NSArray *)ereaArr
{
    if (!_ereaArr) {
        _ereaArr = [NSArray array];
    }
    return _ereaArr;
}
@end
